import cv2 as cv
videofilename = r'D:\photo\vtest.avi'
video = cv.VideoCapture(videofilename)
ret,prev = video.read()
pregray = cv.cvtColor(prev,cv.COLOR_BGR2GRAY)

Feature_params = dict(maxCorners = 200,
qualityLevel = 0.03,
minDistance = 7,
mask = None,
blockSize = 7)
LK_params = dict(winSize = (15,15),
maxLevel = 4,
criteria = (cv.TERM_CRITERIA_EPS|cv.TermCriteria_COUNT,10,0.1))
p0 = cv.goodFeaturesToTrack(pregray,**Feature_params)
while True:
    ret,frame = video.read()
    if not ret:
        break
    gray = cv.cvtColor(frame,cv.COLOR_BGR2GRAY)
    p1,status,err = cv.calcOpticalFlowPyrLK(pregray,gray,p0,None,**LK_params)
    goodpoints = p1[status ==1]
    pregoodpoints = p0[status == 1]

    cap = frame.copy()
    for i,(a,b) in enumerate(zip(goodpoints,pregoodpoints)):
        x0,y0 = a.ravel()
        x1,y1 = b.ravel()
        cv.line(cap,(x1,y1),(x0,y0),(255,0,255),2)
        cv.circle(cap,(x0,y0),1,(255,255,0),2)
        pregray = gray.copy()
        p0 = p1.reshape(-1,1,2)
        cv.imshow('result',cap)

    key = cv.waitKey(30)
    if key==27:
        break
video.release()
cv.destroyAllWindows()